package com.zhfi.dataapply.schedule.quartz;

import com.zhfi.dataapply.entity.job.JobSetting;
import com.zhfi.dataapply.service.JobSettingService;
import org.quartz.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class QuartzManager implements InitializingBean{

    @Value("${default_cron_expression:0 0 7 * * ?}")
    private String default_cron_expression;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobSettingService jobSettingService;

    public void startJob() throws Exception{
        List<JobSetting> jobSettings = jobSettingService.getJobSettings();
        for (JobSetting jobSetting : jobSettings) {
            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(jobSetting.getJobClassName()));
            // 任务名称和组构成任务key
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobSetting.getJobClassName(), jobSetting.getJobGroup()).build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            String cronExpression = jobSetting.getCronExpression();
            if (!StringUtils.hasText(cronExpression)) {
                cronExpression = default_cron_expression;
            }
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobSetting.getJobClassName(), jobSetting.getJobGroup())// 触发器key
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).startNow().build();
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        startJob();
    }
}
